package com.huang.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.huang.enums.UserCodeEnum;
import com.huang.resp.CommonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * 自定义未认证Handler 无效token/token过期 自定义响应
 *
 * @author han
 * @since 2022-01-16 16:13:32
 */
@Log4j2
@Component
public class DefaultAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
       log.info("自定义未认证Handler==>无效token/token过期");
        return Mono.defer(() -> Mono.just(exchange.getResponse())).flatMap(response -> {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            String result = JSONObject.toJSONString(CommonResult.error(UserCodeEnum.TOKEN_EXPIRED));
            DataBuffer buffer = dataBufferFactory.wrap(result.getBytes(Charset.defaultCharset()));
            return response.writeWith(Mono.just(buffer));
        });
    }

}
